#define _CRT_SECURE_NO_WARNINGS 1
#include "Stack.h"

void StackInit(Stack* ps)
{
	assert(ps);
	ps->capacity = 4;
	STDataType* ptr = (STDataType*)malloc(sizeof(STDataType) * (ps->capacity));
	if (ptr == NULL)
	{
		perror("malloc fail");
		return;
	}
	else
	{
		ps->data = ptr;
		ptr = NULL;
		ps->top = 0;
	}
}

void StackDestroy(Stack* ps)
{
	assert(ps);
	free(ps->data);
	ps->data = NULL;
	ps->top = ps->capacity = 0;
}

void StackPush(Stack* ps, STDataType x)
{
	assert(ps);
	if (ps->top == ps->capacity)
	{
		STDataType* ptr = (STDataType*)realloc(ps->data, sizeof(STDataType)* (ps->capacity)*2);
		if (ptr == NULL)
		{
			perror("realloc");
			return;
		}
		else
		{
			ps->data = ptr;
			ptr = NULL;
			ps->capacity *= 2;
		}
	}
	ps->data[ps->top] = x;
	ps->top++;
}

bool StackEmpty(Stack* ps)
{
	assert(ps);
	return ps->top == 0;
}

void StackPop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	ps->top--;
}

STDataType StackTop(Stack* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));

	return ps->data[ps->top - 1];
}

int StackSize(Stack* ps)
{
	assert(ps);
	return ps->top;
}